// redux -> dva
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { getUserLogin, getUserInfo } from '@/services'

const usersModel:UsersModel = {
  namespace: 'users',
  state: {
    token: '', // 保存token
    // roles: [], // 用户角色信息
    // routes: [], // 动态路由
  },
  effects: {
    *getLogin({ payload }, { call, put }) {
      const result = yield call(getUserLogin, { ...payload })
      yield put({
        type: 'updateLogin',
        payload: {token: `${result.tokenHead} ${result.token}`, }
      })
      // 将前端token存放在本地存储中
      localStorage.setItem('token', `${result.data.tokenHead} ${result.data.token}`)
      console.log('result:-----------redux:', result)
      return  result;
    },
    *getUserInfo(payload, { call, put }) {
      console.log('usersModel:', usersModel)
      // 如何在effect中获取state的值；
      const result = yield call(getUserInfo, { ...payload })
      return  result;
    }
  },
  reducers: {
    updateLogin(state, action) {
      return {...state, token: action.payload.token}
    }
  }
}

export default usersModel;



export interface UserState {
  token: string;
}

export interface UsersModel {
  namespace: 'users';
  state: UserState;
  effects: {
    getLogin: Effect;
    getUserInfo: Effect;
  };
  reducers: {
    updateLogin: Reducer<UserState>;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;
  };
  // subscriptions?: { setup: Subscription };
}
